using Microsoft.EntityFrameworkCore;
using PandaWebAPI.Models.ef;

namespace PandaWebAPI.Services
{
    public class PostService : BaseService<Post>, IPostService
    {
        public PostService(PandaSystemContext context) : base(context)
        {
        }

        public async Task<List<Post>> GetPostsByUserIdAsync(Guid userId)
        {
            return await _dbSet
                .Include(p => p.User)
                .Include(p => p.Category)
                .Include(p => p.PostTags)
                    .ThenInclude(pt => pt.Tag)
                .Where(p => p.UserId == userId && p.IsDeleted != true)
                .OrderByDescending(p => p.CreatedAt)
                .ToListAsync();
        }

        public async Task<List<Post>> GetPostsByCategoryIdAsync(Guid categoryId)
        {
            return await _dbSet
                .Include(p => p.User)
                .Include(p => p.Category)
                .Include(p => p.PostTags)
                    .ThenInclude(pt => pt.Tag)
                .Where(p => p.CategoryId == categoryId && p.IsDeleted != true)
                .OrderByDescending(p => p.CreatedAt)
                .ToListAsync();
        }

        public async Task<List<Post>> GetPostsByTagIdAsync(Guid tagId)
        {
            return await _dbSet
                .Include(p => p.User)
                .Include(p => p.Category)
                .Include(p => p.PostTags)
                    .ThenInclude(pt => pt.Tag)
                .Where(p => p.PostTags.Any(pt => pt.TagId == tagId) && p.IsDeleted != true)
                .OrderByDescending(p => p.CreatedAt)
                .ToListAsync();
        }

        public async Task<Post> IncrementViewCountAsync(Guid postId)
        {
            var post = await _dbSet.FindAsync(postId);
            if (post == null)
                throw new KeyNotFoundException($"Post with ID {postId} not found.");

            post.ViewCount = (post.ViewCount ?? 0) + 1;
            await _context.SaveChangesAsync();

            return post;
        }

        public async Task<Post> SoftDeleteAsync(Guid postId)
        {
            var post = await _dbSet.FindAsync(postId);
            if (post == null)
                throw new KeyNotFoundException($"Post with ID {postId} not found.");

            post.IsDeleted = true;
            post.UpdatedAt = DateTime.UtcNow;
            await _context.SaveChangesAsync();

            return post;
        }

        public async Task<List<Post>> GetActivePostsAsync()
        {
            return await _dbSet
                .Include(p => p.User)
                .Include(p => p.Category)
                .Include(p => p.PostTags)
                    .ThenInclude(pt => pt.Tag)
                .Where(p => p.IsDeleted != true)
                .OrderByDescending(p => p.CreatedAt)
                .ToListAsync();
        }

        public async Task<List<Post>> SearchPostsAsync(string searchTerm)
        {
            return await _dbSet
                .Include(p => p.User)
                .Include(p => p.Category)
                .Include(p => p.PostTags)
                    .ThenInclude(pt => pt.Tag)
                .Where(p => p.IsDeleted != true && 
                    (p.Title.Contains(searchTerm) || p.Content.Contains(searchTerm)))
                .OrderByDescending(p => p.CreatedAt)
                .ToListAsync();
        }

        public override async Task<Post> CreateAsync(Post post)
        {
            // 设置默认值
            post.PostId = Guid.NewGuid();
            post.CreatedAt = DateTime.UtcNow;
            post.ViewCount = 0;
            post.IsDeleted = false;

            // 验证必填字段
            if (string.IsNullOrWhiteSpace(post.Title))
                throw new ArgumentException("Post title is required.");
            if (string.IsNullOrWhiteSpace(post.Content))
                throw new ArgumentException("Post content is required.");

            await _dbSet.AddAsync(post);
            await _context.SaveChangesAsync();

            return post;
        }

        public override async Task<Post> UpdateAsync(Post post)
        {
            var existingPost = await _dbSet.FindAsync(post.PostId);
            if (existingPost == null)
                throw new KeyNotFoundException($"Post with ID {post.PostId} not found.");

            // 更新字段
            existingPost.Title = post.Title;
            existingPost.Content = post.Content;
            existingPost.CategoryId = post.CategoryId;
            existingPost.UpdatedAt = DateTime.UtcNow;

            // 验证必填字段
            if (string.IsNullOrWhiteSpace(existingPost.Title))
                throw new ArgumentException("Post title is required.");
            if (string.IsNullOrWhiteSpace(existingPost.Content))
                throw new ArgumentException("Post content is required.");

            await _context.SaveChangesAsync();

            return existingPost;
        }

        public override async Task<bool> DeleteAsync(Guid id)
        {
            var post = await _dbSet
                .Include(p => p.Comments)
                .Include(p => p.Likes)
                .Include(p => p.PostTags)
                .FirstOrDefaultAsync(p => p.PostId == id);

            if (post == null)
                return false;

            // 软删除
            post.IsDeleted = true;
            post.UpdatedAt = DateTime.UtcNow;
            await _context.SaveChangesAsync();

            return true;
        }
    }
} 